<?php
/**
 * Created by PhpStorm
 * User: 昊天||597767865@qq.com||wx||597767865
 * Date: 2023/7/21
 * Time:8:44
 */

namespace app\common\utils;


use think\Log;
use WeChatPay\Crypto\Rsa;
use WeChatPay\Formatter;

class WechatPayUtil
{

    protected $config;
    public $aesKey = '1F0C281A1508DA2C1F19165AD4A592FB';

    const KEY_LENGTH_BYTE = 32;
    const AUTH_TAG_LENGTH_BYTE = 16;

    public function __construct()
    {
        $this->config = [
            'key_path' => EXTEND_PATH . '/cert/apiclient_key.pem',
            'cert_path' => EXTEND_PATH . '/cert/apiclient_cert.pem',
            'mch_id' => "1661895787",
            'app_id' => config("xcx.appId"),
            'gzh_app_id' => '',
        ];
    }



    /**
     * @notes jsapi支付
     *'attach' 1-订单 2-地址订单
     */
    public function pay($order_no,$money,$openid,$attach='1',$pay_type=1,$notify_url="/api/pay/notify")
    {
        //请求URL
        $url = 'https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi';
        //请求方式
        $http_method = 'POST';
        $appid = $pay_type==1?$this->config['app_id']:$this->config['gzh_app_id'];
        //请求参数
        $data = [
            'appid' => $appid,
            'mchid' => $this->config['mch_id'],
            'description' => '购买',
            'out_trade_no' => $order_no,
            'attach'=>(string)$attach,
            'notify_url' => 'https://' . $_SERVER['HTTP_HOST'] . $notify_url, //回调地址,
            'amount' => [
                'total' => intval($money*100),
                'currency' => "CNY",
            ],
            'payer' => [
                'openid' => $openid
            ]
        ];
        $token = $this->token($url, $http_method, $data, $this->config);//获取token
        $result = $this->https_request($url, json_encode($data), $token);//发送请求
        $res = json_decode($result, true);
        Log::error('支付：');
        Log::error($res);
        if (isset($res['prepay_id'])) {
            $res = $this->makeWxSign($res['prepay_id'], $pay_type);
        }
        return $res;
    }


    /**
     * @notes 生成签名
     */
    public function makeWxSign($prepay_id,$pay_type=1): array
    {
        $merchantPrivateKeyFilePath = "file://".$this->config['key_path'];
        $merchantPrivateKeyInstance = Rsa::from($merchantPrivateKeyFilePath);
        $app_id = $pay_type==1?$this->config['app_id']:$this->config['gzh_app_id'];
        $params = [
            'appId' =>$app_id,
            'timeStamp' => (string)Formatter::timestamp(),
            'nonceStr' => Formatter::nonce(),
            'package' => 'prepay_id='.$prepay_id,
        ];
        $params += ['paySign' => Rsa::sign(
            Formatter::joinedByLineFeed(...array_values($params)),
            $merchantPrivateKeyInstance
        ), 'signType' => 'RSA'];
        return $params;
    }

    /**
     * @notes 获取签名
     */
    public function token($url, $http_method, $data, $config)
    {
        $timestamp = time();//请求时间戳
        $url_parts = parse_url($url);//获取请求的绝对URL
        $nonce = $timestamp . rand('10000', '99999');//请求随机串
        $body = empty($data) ? '' : json_encode((object)$data);//请求报文主体
        $stream_opts = [
            "ssl" => [
                "verify_peer" => false,
                "verify_peer_name" => false,
            ]
        ];
        $apiclient_cert_arr = openssl_x509_parse(file_get_contents($config['cert_path'], false, stream_context_create($stream_opts)));
        $serial_no = $apiclient_cert_arr['serialNumberHex'];//证书序列号
        $mch_private_key = file_get_contents($config['key_path'], false, stream_context_create($stream_opts));//密钥
        $merchant_id = $config['mch_id'];//商户id
        $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
        $message = $http_method . "\n" .
            $canonical_url . "\n" .
            $timestamp . "\n" .
            $nonce . "\n" .
            $body . "\n";
        openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
        $sign = base64_encode($raw_sign);//签名
        $schema = 'WECHATPAY2-SHA256-RSA2048';
        $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
            $merchant_id, $nonce, $timestamp, $serial_no, $sign);//微信返回token
        return $schema . ' ' . $token;
    }

    /**
     * @notes 发送请求
     */
    public function https_request($url, $data, $token)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, (string)$url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //添加请求头
        $headers = [
            'Authorization:' . $token,
            'Accept: application/json',
            'Content-Type: application/json; charset=utf-8',
            'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
        ];
        if (!empty($headers)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**
     * @notes 敏感信息加解密
     */
    public function getEncrypt($str, $config)
    {
        //$str是待加密字符串
        $public_key = file_get_contents($config['cert_path']);
        $encrypted = '';
        if (openssl_public_encrypt($str, $encrypted, $public_key, OPENSSL_PKCS1_OAEP_PADDING)) {
            //base64编码
            $sign = base64_encode($encrypted);
        } else {
            throw new \Exception('encrypt failed');
        }
        return $sign;
    }


    /**
     * 解密
     */
    public function decryptToString($associatedData, $nonceStr, $ciphertext)
    {
        $ciphertext = \base64_decode($ciphertext);
        if (strlen($ciphertext) <= self::AUTH_TAG_LENGTH_BYTE) {
            return false;
        }
        // ext-sodium (default installed on >= PHP 7.2)
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            return \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $this->aesKey);
        }
        // ext-libsodium (need install libsodium-php 1.x via pecl)
        if (function_exists('\Sodium\crypto_aead_aes256gcm_is_available') && \Sodium\crypto_aead_aes256gcm_is_available()) {
            return \Sodium\crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $this->aesKey);
        }
        // openssl (PHP >= 7.1 support AEAD)
        if (PHP_VERSION_ID >= 70100 && in_array('aes-256-gcm', \openssl_get_cipher_methods())) {
            $ctext = substr($ciphertext, 0, -self::AUTH_TAG_LENGTH_BYTE);
            $authTag = substr($ciphertext, -self::AUTH_TAG_LENGTH_BYTE);

            return \openssl_decrypt($ctext, 'aes-256-gcm', $this->aesKey, \OPENSSL_RAW_DATA, $nonceStr,
                $authTag, $associatedData);
        }
        throw new \RuntimeException('AEAD_AES_256_GCM需要PHP 7.1以上或者安装libsodium-php');
    }

}